package com.xiangha.springboot.controller;

import com.xiangha.springboot.pojo.Goods;
import com.xiangha.springboot.pojo.Orders;
import com.xiangha.springboot.pojo.Points;
import com.xiangha.springboot.pojo.Users;
import com.xiangha.springboot.service.impl.GoodsServiceImpl;
import com.xiangha.springboot.service.impl.OrdersServiceImpl;
import com.xiangha.springboot.service.impl.PointsServiceImpl;
import com.xiangha.springboot.service.impl.UsersServiceImpl;
import com.xiangha.springboot.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 *
 * @author itlong
 * @since 2025-09-19 03:40:35
 */
@RestController
public class GoodsController {
    @Autowired
    GoodsServiceImpl goodsService;
    @Autowired
    OrdersServiceImpl ordersService;
    @Autowired
    UsersServiceImpl usersService;
    @Autowired
    PointsServiceImpl pointsService;
    @RequestMapping("/points/hot-goods")
    public List<Goods> getHotGoods(){
        return goodsService.getHotGoods();
    }
    @RequestMapping("/points/exchange")
    public Integer exchange(@RequestBody Goods goods, HttpServletRequest request){
        System.out.println("商品ID"+goods);
        Integer goodsId=goods.getGoodId();
        goodsService.getId(goodsId);
        Goods goods1 = goodsService.getById(goodsId);
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        Orders orders=new Orders();
        orders.setUserId(Integer.parseInt(claims.getId()));
        orders.setGoodId(goodsId);
        orders.setTotalPoints(goods1.getPointPrice());
        orders.setBuyCount(1);
        orders.setStatus(1);
        orders.setCreateTime(new java.util.Date());
        ordersService.save( orders);
        usersService.getById(claims.getId());
        boolean updateSuccess = usersService.update()
                .setSql("total_points = total_points - " + goods1.getPointPrice())
                .eq("user_id", claims.getId())
                .update();
        // 获取更新后的积分余额
        Users updatedUser = usersService.getById(claims.getId());
         updatedUser.getTotalPoints();
        Points points=new Points();
        points.setUserId(Integer.parseInt(claims.getId()));
        points.setAmount(-goods1.getPointPrice());
        points.setReason("积分兑换商品"+"("+goods1.getName()+")");
        points.setCreateTime(new java.util.Date());
        pointsService.save(points);
        return updatedUser.getTotalPoints();
    }
}
